import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import { login as loginApi, logout as logoutApi, getUserInfo as getUserInfoApi } from '@/api/user'

export const useUserStore = defineStore('user', () => {
    const token = ref(getToken())
    const userInfo = ref(getUserInfo())

    const setUserToken = (newToken) => {
        token.value = newToken
        setToken(newToken)
    }

    const setUserData = (info) => {
        userInfo.value = info
        setUserInfo(info)
    }

    const login = async (loginForm) => {
        try {
            const response = await loginApi(loginForm)
            // 根据后端返回格式获取token
            const tokenValue = response.token || response
            setUserToken(tokenValue)
            return Promise.resolve(response)
        } catch (error) {
            return Promise.reject(error)
        }
    }

    const logout = async () => {
        try {
            await logoutApi()
        } catch (error) {
            console.error('登出失败:', error)
        } finally {
            token.value = null
            userInfo.value = null
            removeToken()
            removeUserInfo()
        }
    }

    const getUserData = async () => {
        try {
            const response = await getUserInfoApi()
            setUserData(response)
            return Promise.resolve(response)
        } catch (error) {
            return Promise.reject(error)
        }
    }

    return {
        token,
        userInfo,
        setUserToken,
        setUserData,
        login,
        logout,
        getUserData
    }
}) 